<template>
  <div class="channel-edit">
    <van-cell :border="false">
      <div slot="title" class="title-text">我的频道</div>
       <!-- 注意编辑按钮，使用的是默认插槽default，默认插槽控制的是右侧内容 -->
      <van-button class="edit-btn" size="mini" round type="danger" @click="
      isadd= ! isadd"
       plain

       >{{isadd ? '完成':'编辑'}}</van-button>
    </van-cell>
    <van-grid  class='my-grid' :gutter="10">
      <van-grid-item
      class="grid-item"
        v-for="(value,index) in myChannels"
        :key="index"
        @click='onck(value,index)'
      >
      <van-icon slot="icon" v-show="isadd && !fixedch.includes(value.id)"  name="clear"></van-icon>

        <span class="text" :class="{active:  index === active}" slot="text">

        {{ value.name }}
    </span>

      </van-grid-item>
    </van-grid>
    <!-- 频道推荐 -->
    <van-cell :border="false">
      <div slot="title" class="title-text">频道推荐</div>
    </van-cell>
    <van-grid :gutter="10">
      <van-grid-item
      class="grid-item"
        v-for="value in recmychannel"
        :key="value.id"
        @click="onadd(value)"
        :text="value.name"
      />
    </van-grid>
    <!-- /频道推荐 -->
  </div>
</template>

<script>
import { mapState } from 'vuex'
// 引入本地储存模块
import { setItem } from '@/utils/storage.js'
import { getAllChannels } from '@/api/user.js'
import { addUserChannel, deleteUserChannel } from '@/api/channel.js'
export default {

  name: 'ChannelEdit',
  components: {},
  props: {
    myChannels: {
      type: Array,
      required: true
    },
    active: {
      type: Number,
      required: true
    }
  },
  data () {
    return {

      isadd: false,
      allChannels: [],
      fixedch: [0]
    }
  },
  computed: {
    // 获取user
    ...mapState(['user']),
    // 筛选频道推荐
    recmychannel () {
      return this.allChannels.filter(channel => {
        return !this.myChannels.find(myChannel => myChannel.id === channel.id)
      })
    }
  },
  watch: {},
  created () {
    this.load()
  },
  mounted () {},
  methods: {

    // 加载所有频道
    // 加载所有频道
    async load () {
      try {
        const { data } = await getAllChannels()
        this.allChannels = data.data.channels
        // console.log(data.data.channels);
      } catch (err) {
        this.$toast('获取频道列表数据失败')
      }
    },

    // ,添加到我的频道
    async onadd (value) {
      this.myChannels.push(value)

      if (this.user) {
        // 已登录
        try {
          // 已登录，数据存储到线上
          await addUserChannel({
            id: value.id, // 频道 id
            seq: this.myChannels.length // 频道的 序号
          })
          this.$toast('添加成功')
        } catch (err) {
          console.log(err)
          this.$toast('保存失败')
        }
      } else {
        // 未登陆
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },
    // 切换频道
    async onck (value, index) {
      if (this.isadd) {
      // 编辑状态

        // 2. 如果删除的激活频道之前的频道，则更新激活的频道项

        // 1. 如果是固定频道，则不删除
        if (this.fixedch.includes(index)) {
          return
        }
        if (index <= this.active) {
        // 当前频道被删除之后，上一个频道高亮，并且不关闭弹出层
          this.$emit('vaice', this.active - 1, true)
        }
        // 参数1：要删除的元素的开始索引（包括）
        // 参数2：删除的个数，如果不指定，则从参数1开始一直删除到最后
        this.myChannels.splice(index, 1)

        // 持久化
        try {
          if (this.user) {
            // 已登录，将数据存储到线上
            await deleteUserChannel(value.id)
          } else {
            // 未登录，将数据存储到本地
            setItem('TOUTIAO_CHANNELS', this.myChannels)
          }
        } catch (err) {
          console.log(err)
          this.$toast('删除频道失败，请稍后重试')
        }
      } else {
      // 非编辑状态

        this.$emit('vaice', index, false)
      }
    }
  }
}
</script>

<style scoped lang="less">
.channel-edit {
	padding: 85px 0;
}
.channel-edit {
	padding: 85px 0;

    .title-text {
		font-size: 32px;
		color: #333333;
	}

	.edit-btn {
		width: 104px;
		height: 48px;
		font-size: 26px;
		color: #f85959;
		border: 1px solid #f85959;
	}
}
/deep/ .grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
        white-space: nowrap;
        background-color: #f4f5f6;
        .van-grid-item__text {
            font-size: 28px;
            color: #222;

        }
         .van-grid-item__icon-wrapper {
            position: unset;
        }
    }
}

/deep/ .recommend-grid {
    .grid-item {
        .van-grid-item__content {
            flex-direction: row;
            .van-icon-plus {
                font-size: 28px;
                margin-right: 6px;
            }
            .van-grid-item__text {
                margin-top: 0;
            }
        }
    }
}
/deep/ .my-grid {
    .grid-item {
        .van-icon-clear {
            position: absolute;
            right: -10px;
            top: -10px;
            font-size: 30px;
            color: #cacaca;
            z-index: 2;
        }
    }
}
/deep/ .grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
        white-space: nowrap;
        background-color: #f4f5f6;
        .van-grid-item__text,
        .text  {
            font-size: 28px;
            color: #222;
            margin-top: 0;
        }
        .active {
            color: red;
        }
    }
}
</style>
